<template>
	<view :style="{height:PhoneInfo.windowHeight + 'px',width:PhoneInfo.windowWidth + 'px'}">
		<view class="topxuanz">
			<!-- 时间范围 -->
			<view @click="selectiontime(0)" style="margin-left: 6%;" class="time">
				{{this.$utils.getTime(Number(this.startTimeValue),0)}}
			</view>
			<text> - </text>
			<view @click="selectiontime(1)" class="time">
				{{this.$utils.getTime(Number(this.endTimeValue),0)}}
			</view>
			<view class="huizhi">
				<u-icon name="edit-pen" label="绘制" size="28" @click="draw"></u-icon>
			</view>
			<!-- 自定义时间 -->
			<view class="diytime" @click="showtime=true;canvasshow=false">{{timetext}}</view>
			<!-- 批量修改阈值 -->
			<view class="altervalue" @click="alter">批量修改阈值</view>
		</view>
		<!-- 开始时间 -->
		<u-datetime-picker ref="datetimePicker" title="开始时间" :maxDate='new Date().getTime()'
			:minDate='new Date().getTime()-15552000000' :show="showStartTime" v-model="this.startTimeValue"
			mode="datetime" @confirm='startconfirm' @cancel='showStartTime=false;canvasshow=true'>
		</u-datetime-picker>
		<!-- 结束时间 -->
		<u-datetime-picker ref="datetimePicker" title="结束时间" :maxDate='new Date().getTime()'
			:minDate='new Date().getTime()-15552000000' :show="showEndTime" v-model="this.endTimeValue" mode="datetime"
			@confirm='endconfirm' @cancel='showEndTime=false;canvasshow=true'>
		</u-datetime-picker>
		<!--自定义时间选择 -->
		<u-picker closeOnClickOverlay :immediateChange='true' @cancel="showtime = false;canvasshow=true"
			@confirm="timeconfirm" :show="showtime" :columns="columns" keyName="name"></u-picker>
		<!-- 趋势图 -->
		<uni-ec-canvas v-show="canvasshow" class="uni-canvas" force-use-old-canvas="true" id="uni-ec-canvas"
			ref="canvas" canvas-id="uni-ec-canvas" :ec="ec">
		</uni-ec-canvas>
	</view>
</template>

<script>
	import uniEcCanvas from '@/components/uni-ec-canvas/uni-ec-canvas.vue'
	import * as echarts from '@/components/uni-ec-canvas/echarts'
	let chart = null
	export default {
		components: {
			uniEcCanvas
		},
		data() {
			return {
				ec: {
					lazyLoad: true, //是否懒加载
				},
				option: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					], //颜色
					toolbox: {
						show: true, //是否显示工具栏组件
						right: "3%", //右距离
						top: "35%", //上距离
						itemSize: 23, //工具大小
						orient: "vertical", //工具朝向
						itemGap: 20, //工具之间的间隔
						showTitle: false, //不显示标题
						feature: {
							brush: {
								type: ['lineX'] //开启横向选择功能
							},
							//自定义还原事件
							myTool: {
								icon: 'M3.8,33.4 M47,18.9h9.8V8.7 M56.3,20.1 C52.1,9,40.5,0.6,26.8,2.1C12.6,3.7,1.6,16.2,2.1,30.6 M13,41.1H3.1v10.2 M3.7,39.9c4.2,11.1,15.8,19.5,29.5,18 c14.2-1.6,25.2-14.1,24.7-28.5',
								onclick: () => {
									this.restore();
								}
							},
						}
					},
					brush: { //刷选
						transformable: false,
						throttleDelay: 500,
						throttleType: 'debounce',
						xAxisIndex: 'all',
						outOfBrush: {
							colorAlpha: 0.1
						}
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line' //指示器类型
						},
						formatter: function(params) {
							var text = params[0].name
							for (let item of params) {
								if (item.value == 'undefined' || item.value == undefined || item.value == '') {
									item.value = '无'
								}
								text += '\n' + item.seriesName + ' : ' + item.value
							}
							return text
						}
					},
					legend: {
						show: true,
						top: "16%",
						width: '50%',
						data: []
					},
					xAxis: {
						type: 'category', //类目轴
						axisTick: {
							alignWithLabel: true //保证刻度线和标签对齐
						},
						data: [] //x轴的数据(时间)
					},
					dataZoom: {
						type: 'inside',
						zoomLock: true,
						start: 50,
						end: 100
					},
					grid: {
						top: '32%',
						bottom: '8%',
						left: '9%',
						right: '12%',
					},
					yAxis: [], //y轴
					series: [], //趋势图数据
				},
				canvasshow: true,
				trendstarttime: '', //趋势图开始时间
				trendcurrenttime: '', //趋势图当前屏幕的开始时间
				trendendtime: '', //趋势图结束时间
				timetext: '自定义时间', //时间文本内容
				timenumber: 259200000,
				showtime: false, //是否显示弹窗
				columns: [ //弹窗选项
					[{
						id: 86400000,
						name: '一天',
					}, {
						id: 604800000,
						name: '一周',
					}]
				],
				entrust: '', //是否是授权设备
				scrollLoadingStatus: true, //趋势图翻页防抖处理
				savedata: true, //true表示保存,false表示不保存
				restoredata: '',
				indexdata: '', //指标列表
				PhoneInfo: '',
				showStartTime: false,
				startTimeValue: '',
				showEndTime: false,
				endTimeValue: '',
				showwavetime: false,
			}
		},
		onLoad() {
			this.PhoneInfo = this.$utils.GetPhoneInfo();
			this.indexdata = this.$store.state.ContrastTrendChart;
			if (this.indexdata[0].PointFeatureUnit == '') {
				uni.setNavigationBarTitle({
					title: '指标对比趋势图' + '-' + this.indexdata[0].PointFeatureName
				})
			} else if (this.indexdata[0].PointFeatureUnit == 'ma') {
				uni.setNavigationBarTitle({
					title: '指标对比趋势图' + '-' + this.indexdata[0].PointFeatureName + '(%)'
				})
			} else {
				uni.setNavigationBarTitle({
					title: '指标对比趋势图' + '-' + this.indexdata[0].PointFeatureName + '(' + this.indexdata[0]
						.PointFeatureUnit + ')'
				})
			}
			//获取将测点趋势图页面处理好的时间传递到当前页面
			this.trendcurrenttime = this.indexdata[0].currentTime;
			this.trendstarttime = this.indexdata[0].startTime;
			this.trendendtime = this.indexdata[0].endTime;
			this.$store.commit('alterContrastTrendChart', '');
		},
		onReady() {
			this.getServerData();
		},
		methods: {
			//自定义时间
			timeconfirm(e) {
				//保存还原数据
				this.savedata = true;
				this.timetext = e.value[0].name;
				this.timenumber = e.value[0].id;
				this.showtime = false;
				this.canvasshow = true;
				if (this.timenumber == 86400000) {
					this.trendstarttime = this.$utils.getTime(new Date().getTime() - this.timenumber * 3, 0);
				} else {
					this.trendstarttime = this.$utils.getTime(new Date().getTime() - this.timenumber * 2, 0);
				}
				this.trendcurrenttime = this.$utils.getTime(new Date().getTime() - this.timenumber, 0);
				this.trendendtime = this.$utils.getTime(new Date().getTime(), 0);
				this.getServerData();
			},
			//时间选择传值
			selectiontime(value) {
				if (value == 0) {
					this.canvasshow = false;
					this.showStartTime = true;
					this.$store.commit('altertimedata', this.startTimeValue);
				} else {
					this.canvasshow = false;
					this.showEndTime = true;
					this.$store.commit('altertimedata', this.endTimeValue);
				}
			},
			//开始时间确定
			startconfirm(e) {
				this.startTimeValue = e.value;
				this.showStartTime = false;
				this.canvasshow = true;
				var millisecond = this.endTimeValue - this.startTimeValue;
				if (millisecond <= 0) {
					uni.showToast({
						icon: "none",
						title: "时间范围选择有误,请重新选择!",
						mask: true,
					})
					return
				}
				if (millisecond > 2592000000) {
					uni.showToast({
						icon: "none",
						title: "选择的时间跨度最多不能超过一个月,请重新选择!",
						mask: true,
					})
					return
				}
			},
			// 结束时间确定
			endconfirm(e) {
				this.endTimeValue = e.value;
				this.showEndTime = false;
				this.canvasshow = true;
				var millisecond = this.endTimeValue - this.startTimeValue;
				if (millisecond <= 0) {
					uni.showToast({
						icon: "none",
						title: "时间范围选择有误,请重新选择!",
						mask: true,
					})
					return
				}
				if (millisecond > 2592000000) {
					uni.showToast({
						icon: "none",
						title: "选择的时间跨度最多不能超过一个月,请重新选择!",
						mask: true,
					})
					return
				}
			},
			//根据选择的时间绘制趋势图
			draw() {
				this.timenumber = this.endTimeValue - this.startTimeValue;
				if (this.timenumber < 0) {
					uni.showToast({
						icon: "none",
						title: "时间范围选择有误,请重新选择!",
						mask: true,
					})
					return
				}
				if (this.timenumber > 2592000000) {
					uni.showToast({
						icon: "none",
						title: "选择的时间跨度最多不能超过一个月,请重新选择!",
						mask: true,
					})
					return
				}
				this.trendstarttime = this.$utils.getTime(this.startTimeValue - this.timenumber, 0);
				this.trendcurrenttime = this.$utils.getTime(this.startTimeValue, 0);
				this.trendendtime = this.$utils.getTime(this.endTimeValue, 0);
				//判断当前接口的请求时间是否超过三个月
				if (new Date().getTime() - 7776000000 > this.startTimeValue - this.timenumber) {
					uni.showModal({
						content: '您即将查询三个月之前的数据,可能需要花费较长的时间,是否继续?',
						cancelText: '否',
						confirmText: '是',
						success: function(res) {
							if (res.confirm) {
								var that = this;
								//保存还原数据
								that.savedata = true;
								that.timetext = '自定义时间';
								that.getServerData();
							}
						}.bind(this)
					});
				} else {
					//保存还原数据
					this.savedata = true;
					this.timetext = '自定义时间';
					this.getServerData();
				}
			},
			//批量修改阈值
			alter() {
				this.$store.commit('alterContrastTrendChart', this.indexdata)
				uni.redirectTo({
					url: '/pages/equipment/batchChange'
				})
			},
			initChart(canvas, width, height, canvasDpr) {
				//显示趋势图
				this.canvasshow = true;
				chart = echarts.init(canvas, null, {
					width: width,
					height: height,
					devicePixelRatio: canvasDpr
				})
				canvas.setChart(chart)
				chart.setOption(this.option)
				//保留原始数据
				if (this.savedata) {
					this.restoredata = JSON.parse(JSON.stringify(this.option));
				}
				//获取初始时间
				var optinfo = chart.getOption();
				this.startTimeValue = new Date(this.option.xAxis.data[optinfo.dataZoom[0].startValue].replace(/-/g, '/'))
					.getTime();
				this.endTimeValue = new Date(this.option.xAxis.data[optinfo.dataZoom[0].endValue].replace(/-/g, '/'))
					.getTime();
				//“选框添加完毕”事件
				chart.on('brushEnd', (param) => {
					this.startTimeValue = new Date(this.option.xAxis.data[param.areas[0].coordRange[0]].replace(
						/-/g, '/')).getTime();
					this.endTimeValue = new Date(this.option.xAxis.data[param.areas[0].coordRange[1]].replace(/-/g,
						'/')).getTime();
					this.timenumber = this.endTimeValue - this.startTimeValue;
					this.trendstarttime = this.$utils.getTime(this.startTimeValue - this.timenumber, 0);
					this.trendcurrenttime = this.$utils.getTime(this.startTimeValue, 0);
					this.trendendtime = this.$utils.getTime(this.endTimeValue, 0);
					if (new Date().getTime() - 7776000000 > this.startTimeValue - this.timenumber) {
						uni.showModal({
							content: '您即将查询三个月之前的数据,可能需要花费较长的时间,是否继续?',
							cancelText: '否',
							confirmText: '是',
							success: function(res) {
								if (res.confirm) {
									var that = this;
									//不保存还原数据
									that.savedata = false;
									that.timetext = '自定义时间';
									that.getServerData();
								}
							}.bind(this)
						});
					} else {
						//不保存还原数据
						this.savedata = false;
						this.timetext = '自定义时间';
						this.getServerData();
					}
				})
				//滑动事件
				chart.on('datazoom', (param) => {
					//获取当前屏幕的显示时间
					var opti = chart.getOption()
					this.startTimeValue = new Date(this.option.xAxis.data[opti.dataZoom[0].startValue].replace(
						/-/g, '/')).getTime();
					this.endTimeValue = new Date(this.option.xAxis.data[opti.dataZoom[0].endValue].replace(/-/g,
						'/')).getTime();
					//翻页
					if (opti.dataZoom[0].start == 0) {
						//防抖
						if (this.scrollLoadingStatus == false) {
							return;
						} else {
							this.scrollLoadingStatus = false;
							var timenewdata = 0;
							if (this.timenumber == 86400000) {
								timenewdata = new Date(this.trendstarttime.replace(/-/g, '/')).getTime() -
									this.timenumber * 3;
							} else {
								timenewdata = new Date(this.trendstarttime.replace(/-/g, '/')).getTime() -
									this.timenumber * 2;
							}
							//判断时间是否超过三个月
							if (new Date().getTime() - 7776000000 > timenewdata) {
								uni.showModal({
									content: '您即将查询三个月之前的数据,可能需要花费较长的时间,是否继续?',
									cancelText: '否',
									confirmText: '是',
									success: function(res) {
										if (res.confirm) {
											var that = this;
											this.getNewData()
										}
									}.bind(this)
								});
							} else {
								this.getNewData()
							}
						}
					}
				})
				return chart
			},
			//获取趋势图数据
			getServerData() {
				//每次指标更换或者时间改变的时候,都会将防抖处理改为true
				this.scrollLoadingStatus = true;
				this.option.yAxis = []; //清除y轴
				this.option.xAxis.data = []; //清除时间
				this.option.series = []; ///清除数据
				// 将选择的时间加到indexdata中
				for (let items of this.indexdata) {
					items.endTime = this.trendendtime;
					items.currentTime = this.trendcurrenttime;
					items.startTime = this.trendstarttime;
				}
				uni.showLoading({
					title: "加载中...",
					mask: true,
				});
				setTimeout(() => {
					uni.request({
						url: getApp().globalData.serverAddress + this.$uri.Uri_indexcontrast,
						data: this.indexdata,
						dataType: "json",
						method: "POST",
						success: (res) => {
							if (res.statusCode !== 200) {
								uni.showToast({
									icon: "none",
									title: "服务器错误,请联系技术支持人员!",
									mask: true,
								})
								return
							}
							const response = res.data
							if (response.code == 0) {
								if (response.count == 0) {
									this.loadingnumber = '0'
									uni.showToast({
										icon: "none",
										title: "所选时间段暂无数据,请重新选择! ",
										mask: true,
									})
								} else {
									var serial = 0;
									var position = 'left';
									var offset = 0;
									var namegap = 15;
									var maxvalue = '';
									var minvalue = 0;
									if (this.indexdata[0].PointFeatureName == '冲击能量' || this
										.indexdata[
											0].PointFeatureName ==
										'冲击峰值') {
										minvalue = 45;
									} else if (this.indexdata[0].PointFeatureName ==
										'周期冲击能量') {
										minvalue = 14;
									}
									//时间
									this.option.xAxis.data = response.data.categories;
									//改变组件距离左右的距离
									if (response.data.trends.length == 5 || response.data
										.trends
										.length == 6) {
										this.option.grid.left = '16%';
										this.option.grid.right = '22%';
										this.option.grid.top = '37%';
									} else if (response.data.trends.length == 3 || response
										.data.trends
										.length == 4) {
										this.option.grid.left = '12%';
										this.option.grid.right = '17%';
										this.option.grid.top = '35%';

									} else {
										this.option.grid.left = '9%';
										this.option.grid.right = '12%';
										this.option.grid.top = '32%';
									}
									//获取所有数据的最大值
									for (var value of response.data.trends) {
										if (maxvalue == '') {
											maxvalue = Math.max.apply(null, value.resultDatas);
										} else {
											if (maxvalue <= Math.max.apply(null, value
													.resultDatas)) {
												maxvalue = Math.max.apply(null, value
													.resultDatas);
											}
										}
									}
									for (var item of response.data.trends) {
										this.option.legend.data.push(item.equipmentName +
											' - ' + item
											.pointName);
										//y轴
										this.option.yAxis.push({
											type: 'value',
											name: item.equipmentName + ' - ' + item
												.pointName,
											offset: offset,
											position: position,
											max: (maxvalue * 1.1).toFixed(2),
											min: minvalue,
											nameGap: namegap,
											splitLine: {
												show: false
											}
										})
										//改变y轴的位置
										if (position == 'left') {
											position = 'right';
										} else {
											position = 'left';
											offset += 40;
											namegap += 16;;
										}
										//y轴数据
										this.option.series.push({
											name: item.equipmentName + ' - ' + item
												.pointName,
											type: 'line',
											yAxisIndex: serial,
											smooth: true,
											emphasis: {
												focus: 'series'
											},
											connectNulls: true,
											data: item.resultDatas,
											color: this.option.color[serial],
										})
										serial += 1
									}
									uni.hideLoading();
									//定位显示区域
									this.option.dataZoom.end = 100;
									this.option.dataZoom.start = 100 - Math.round(response
										.count /
										response.data.categories.length * 100);
									this.$refs.canvas.init(this.initChart)
								}
							} else {
								uni.showToast({
									icon: "none",
									title: res.data.msg,
									mask: true,
								})
							}
						},
						fail() {
							uni.showToast({
								icon: "none",
								title: "加载失败! ",
								mask: true,
							})
						}
					})
				}, 1000);
			},
			//翻页
			getNewData() {
				this.trendendtime = this.trendstarttime;
				this.trendcurrenttime = this.$utils.getTime(new Date(this.trendstarttime.replace(/-/g, '/'))
					.getTime() -
					this.timenumber, 0);
				if (this.timenumber == 86400000) {
					this.trendstarttime = this.$utils.getTime(new Date(this.trendstarttime.replace(/-/g, '/'))
						.getTime() -
						this.timenumber * 3, 0);
				} else {
					this.trendstarttime = this.$utils.getTime(new Date(this.trendstarttime.replace(/-/g, '/'))
						.getTime() -
						this.timenumber * 2, 0);
				}
				// 将选择的时间加到indexdata中
				for (let items of this.indexdata) {
					items.endTime = this.trendendtime;
					items.currentTime = this.trendcurrenttime;
					items.startTime = this.trendstarttime;
				}
				uni.showLoading({
					title: "加载中...",
					mask: true,
				});
				setTimeout(() => {
					uni.request({
						url: getApp().globalData.serverAddress + this.$uri.Uri_indexcontrast,
						data: this.indexdata,
						dataType: "json",
						method: "POST",
						success: (res) => {
							if (res.statusCode !== 200) {
								uni.showToast({
									icon: "none",
									title: "服务器错误,请联系技术支持人员! ",
									mask: true,
								})
								return
							}
							const response = res.data;
							if (response.code == 0) {
								if (response.count == 0) {
									uni.showToast({
										icon: "none",
										title: "没有更多数据了! ",
										mask: true,
									})
								} else {
									var serial = 0;
									var maxvalue = '';
									//时间拼接
									this.option.xAxis.data = response.data.categories.concat(
										this
										.option
										.xAxis.data);
									//获取所有数据的最大值
									for (var value of response.data.trends) {
										if (maxvalue == '') {
											maxvalue = Math.max.apply(null, value.resultDatas);
										} else {
											if (maxvalue <= Math.max.apply(null, value
													.resultDatas)) {
												maxvalue = Math.max.apply(null, value
													.resultDatas);
											}
										}
									}
									for (var item of response.data.trends) {
										// 和上一次的最大值进行比较
										if (maxvalue <= this.option.yAxis[serial].max) {
											this.option.yAxis[serial].max = (this.option.yAxis[
													serial]
												.max * 1.1).toFixed(2);
										}
										this.option.series[serial].data = item.resultDatas
											.concat(this.option.series[serial].data);
										serial++
									}
									uni.hideLoading();
									//定位显示区域
									this.option.dataZoom.end = Math.round(response.count / this
										.option.xAxis
										.data.length * 100);
									this.option.dataZoom.start = Math.round(this.option
										.dataZoom.end /
										2);
									//绘制趋势图
									this.$refs.canvas.init(this.initChart)
									//防抖处理
									this.scrollLoadingStatus = true;
								}
							} else {
								uni.showToast({
									icon: "none",
									title: res.data.msg,
									mask: true,
								})
							}
						},
						fail() {
							uni.showToast({
								icon: "none",
								title: "加载失败！",
								mask: true,
							})
						}
					})
				}, 1000);
			},
			//还原
			restore() {
				this.option.xAxis = JSON.parse(JSON.stringify(this.restoredata.xAxis));
				this.option.yAxis = JSON.parse(JSON.stringify(this.restoredata.yAxis));
				this.option.series = JSON.parse(JSON.stringify(this.restoredata.series));
				this.option.dataZoom = JSON.parse(JSON.stringify(this.restoredata.dataZoom));
				this.scrollLoadingStatus = true;
				this.$refs.canvas.init(this.initChart)
			}
		}
	};
</script>
<style scoped lang="scss">
	// 趋势图
	.uni-canvas {
		width: 100%;
		height: 100%;
	}

	//顶部操作栏
	.topxuanz {
		margin-top: 1%;
		width: 100%;
		position: fixed;
		z-index: 9999;
	}

	//开始和结束时间选择器
	.topxuanz .time {
		display: inline-block;
		width: 23%;
		margin: 0 1%;
		height: 30px;
		line-height: 30px;
		font-size: 16px;
		text-align: center;
		color: black;
		border: 1px solid;
		border-radius: 15px;
	}

	.topxuanz .huizhi {
		position: fixed;
		top: 4%;
		display: inline-block;
	}

	.diytime {
		margin-left: 9%;
		display: inline-block;
		border: 1px solid #3c9cff;
		height: 30px;
		line-height: 30px;
		width: 12%;
		text-align: center;
		font-size: 15px;
		border-radius: 15px;
		color: #3c9cff;
	}

	.altervalue {
		margin-left: 2%;
		display: inline-block;
		border: 1px solid #f9ae3d;
		height: 30px;
		line-height: 30px;
		width: 15%;
		text-align: center;
		font-size: 15px;
		border-radius: 15px;
		color: #f9ae3d;
	}
</style>